package com.ceres.system.controller;

import com.ceres.entity.PageResult;
import com.ceres.entity.Result;
import com.ceres.entity.StatusCode;
import com.ceres.system.dao.RoleMapper;
import com.ceres.system.pojo.Role;
import com.ceres.system.service.RoleService;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @PostMapping("/add")
    public Result add(Integer[] menuIds,@RequestBody Role role){
        try {
            roleService.addRole(menuIds,role);
            return new Result(true, StatusCode.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR);
        }
    }

    @DeleteMapping("/delete/{id}")
    public Result deleteRole(@PathVariable("id") Integer id){
        try {
        roleService.deleteRoleById(id);
        return new Result(true, StatusCode.OK);
        } catch (Exception e) {
        e.printStackTrace();
        return new Result(false, StatusCode.ERROR);
        }
    }

    @GetMapping("/queryRole")
    public Result queryRole(@RequestParam Map queryCondition,@RequestParam(required = false,defaultValue = "1") int page,@RequestParam(required = false,defaultValue = "5") int size){
        try {
            Page<Role> pageList = roleService.queryRole(queryCondition, page, size);
            PageResult pageResult = new PageResult(pageList.getTotal(), pageList.getResult());
            return new Result(true,StatusCode.OK,pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR);
        }

    }

    @PutMapping("/update")
    public Result updateRole(@RequestBody Role role,Integer[] menuIds){
        try {
            roleService.updateRole(role,menuIds);
            return new Result(true,StatusCode.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR);
        }
    }

    /**
     * 根据角色查找后台用户
     * @return
     */
    @GetMapping("/findAdminRole")
    public Result findAdminRole(){
        try {
            roleService.findAll();
            return new Result(true,StatusCode.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR);
        }
    }

    /**
     * 根据角色查找平台用户
     * @return
     */
    @GetMapping("/findUserRole")
    public Result findUserRole(){
        try {
            roleService.findUserRole();
            return new Result(true,StatusCode.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR);
        }
    }

}
